class CommentsController < ApplicationController
    before_action :logged_in_user, only: :create
    before_action :correct_user, only: :destroy
    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(com_params)
        @comment.user_id = session[:user_id]
        if @comment.save
            flash[:success] = "评论成功！"
        else
            flash[:fail] = @comment.errors.full_messages.first
        end
        redirect_to post_path(@post)
    end
    private
    def logged_in_user
        unless logged_in?
          flash[:fail] = "权限不足"
          redirect_to login_url
        end
    end
    def correct_user
        @user = User.find(params[:id])
        redirect_to(root_url) and flash[:fail] = "权限不足" unless current_user?(@user)
    end
    def com_params
        params.require(:comment).permit(:content,:user_id)
    end
end
